package m.jclecai.com.base;


import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jaeger.library.StatusBarUtil;
import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import m.jclecai.com.R;
import m.jclecai.com.activity.LoginActivity;
import m.jclecai.com.bean.RegisterBean;
import m.jclecai.com.bean.UserBean;
import m.jclecai.com.constant.Constant_Result;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.listener.Callback;
import m.jclecai.com.utils.MD5;
import m.jclecai.com.utils.MyToast;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.utils.http.SystemUtils;

/**
 * 相同的部分由父类去实现
 * 不同的部分制定规则
 */
public abstract class BaseFragment extends ISuperBaseFragment {
    @Nullable
    @BindView(R.id.tv_back)
    protected TextView tvBack;
    @Nullable
    @BindView(R.id.tv_mid_title)
    protected TextView tvMidTitle;
    @Nullable
    @BindView(R.id.tv_right_option)
    protected TextView tvRightOption;
    //标题栏容器
    @Nullable
    @BindView(R.id.rl_bar)
    protected RelativeLayout rlBar;
    //正文内容容器
    protected FrameLayout vBody;
    //界面容器
    @Nullable
    @BindView(R.id.activity_base)
    protected RelativeLayout activityBase;
    @BindView(R.id.iv_title_icon)
    protected ImageView ivTitleIcon;
    @Nullable
    @BindView(R.id.v_title_fill)
    protected View v_title_fill;

    Unbinder unbinder;
    private Callback callback;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = View.inflate(getActivity(), R.layout.activity_base, null);
        vBody = (FrameLayout) inflate.findViewById(R.id.v_body);
        View.inflate(getActivity(), getLayoutId(), vBody);
        initLoadingView(vBody);
        unbinder = ButterKnife.bind(this, inflate);
        tvBack.setVisibility(View.INVISIBLE);
        tvMidTitle.setVisibility(View.INVISIBLE);
        tvRightOption.setVisibility(View.INVISIBLE);
        ivTitleIcon.setVisibility(View.GONE);
        initView();
        initData();
        initListener();
        int color = getTitleBackgroundColor();
        if (tvBack.getVisibility() == View.INVISIBLE
                && tvMidTitle.getVisibility() == View.INVISIBLE
                && tvRightOption.getVisibility() == View.INVISIBLE) {
            rlBar.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.b));
            rlBar.setVisibility(View.GONE);
            v_title_fill.setVisibility(View.GONE);
            if (color == -1)
                color = R.color.b;
            StatusBarUtil.setColorNoTranslucent(getActivity(), ContextCompat.getColor(getActivity(), color));
        } else {
            if (color == -1)
                color = R.color.color_home;
            StatusBarUtil.setColorNoTranslucent(getActivity(), ContextCompat.getColor(getActivity(), color));
        }
        return inflate;
    }

    protected void initLoadingView(View vBody) {

    }

    //是否允许body覆盖title
    protected void allowBodyCoverTitle(boolean bool){
        v_title_fill.setVisibility(bool?View.GONE:View.VISIBLE);
        if (tvBack.getVisibility() == View.INVISIBLE
                && tvMidTitle.getVisibility() == View.INVISIBLE
                && tvRightOption.getVisibility() == View.INVISIBLE) {
            v_title_fill.setVisibility(View.GONE);
        }
    }

    @Override
    public void initData() {
    }

    @Override
    public void initView() {
    }

    @Override
    public void initListener() {
    }

    public abstract int getLayoutId();

    protected void setTitle(String text) {
        setTitle(text, -1);
    }

    //右边按钮的文本 drawable -1 代表不加图案
    @Override
    protected void setTitle(String txt, int drawable) {
        tvMidTitle.setVisibility(View.VISIBLE);
        tvMidTitle.setText(txt);
        if (drawable > -1) {
            ivTitleIcon.setVisibility(View.VISIBLE);
            ivTitleIcon.setImageResource(drawable);
        }
    }

    //左边按钮 = 返回
    protected void leftOptionText(String text) {
        leftOptionText(text, -1);
    }

    @Override
    protected void leftOptionText(String text, int drawable) {
        tvBack.setVisibility(View.VISIBLE);
        tvBack.setText(text);
        if (drawable > -1)
            tvBack.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getActivity(), drawable), null, null, null);
    }

    protected void rightOptionText(String text) {
        rightOptionText(text, -1);
    }

    @Override
    protected void rightOptionText(String text, int drawable) {
        tvRightOption.setVisibility(View.VISIBLE);
        tvRightOption.setText(text);
        if (drawable > -1)
            tvRightOption.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getActivity(), drawable), null, null, null);
    }

    protected void startAnimation(View view, int animation) {
        Animation operatingAnim = AnimationUtils.loadAnimation(getActivity(), animation);
        LinearInterpolator lin = new LinearInterpolator();
        operatingAnim.setInterpolator(lin);
        view.startAnimation(operatingAnim);
    }


    protected boolean isLogin() {
        return PreferenceUtil.readBoolean(getActivity(), "login_state", false);
    }

    @Override
    protected int getTitleBackgroundColor() {
        return R.color.color_home;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (unbinder != null) {
            unbinder.unbind();
        }
    }

    protected void checkLogin(Callback callback) {
        this.callback = callback;
        if (!isLogin()) {
            startActivityForResult(new Intent(getActivity(), LoginActivity.class), Constant_Result.NEEDLOGIN);
        } else {
            callback.callbackSuccess();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant_Result.NEEDLOGIN) {
            if (resultCode == Activity.RESULT_OK) {
                if (callback != null)
                    callback.callbackSuccess();
            } else {
                if (callback != null)
                    callback.callbackField();
            }
        }
    }

    //自动登录
    protected void logIn(String user, String password, final Callback callback) {
        this.callback = callback;
        //收起软键盘
        showDialog();
        //登录
        final String userPass = MD5.getMD5(password);
        final Map<String, String> pair = new HashMap<String, String>();
        pair.put("user", user);
        pair.put("password", userPass);
        pair.put("version", SystemUtils.getCurrentVersionCode(getActivity()));
        pair.put("channel", "android_"+ Build.VERSION.RELEASE+"_"+Build.MODEL);
        HttpManager.postAsyn(Constant_Url.LOGIN_URL, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                if (callback != null)
                    callback.callbackField();
                //失败
                MyToast.showToast(getActivity(), "无法连接服务器");
                dissDialog();
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                //登陆成功
                RegisterBean registerBean = FastOk.get(response, RegisterBean.class);
                if (registerBean == null) {
                    if (callback != null)
                        callback.callbackField();
                    return;
                }
                MyToast.showToast(getActivity(), registerBean.getMessage());
                if ("0".equals(registerBean.getStatus())) {
                    loadUserInfo(pair);
                } else {
                    if (callback != null)
                        callback.callbackField();
                }
            }
        }, pair);
    }

    //登录后需要加载用户信息
    protected void loadUserInfo(final Map<String, String> pair) {
        showDialog();
        HttpManager.postAsyn(Constant_Url.GET_USER_INFO, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                if (callback != null)
                    callback.callbackField();
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                UserBean userBean = FastOk.get(response, UserBean.class);
                if(userBean != null) {
                    if ("1011".equals(userBean.getStatus())) {
                        MyToast.showToast(getActivity(), "获取用户信息失败！");
                        PreferenceUtil.writeUser(getActivity(), null);
                        if (callback != null)
                            callback.callbackField();
                    } else {
                        PreferenceUtil.setAccount(getActivity(), userBean.getPhone());
                        PreferenceUtil.setUserName(getActivity(), userBean.getUsername());
                        PreferenceUtil.setPassword(getActivity(), pair.get("password"));
                        PreferenceUtil.setLoginStatus(getActivity(), true);
                        PreferenceUtil.writeUser(getActivity(), userBean);
                        if (callback != null)
                            callback.callbackSuccess();
                    }
                } else {
                    MyToast.showToast(getActivity(), getString(R.string.error_network));
                    if (callback != null)
                        callback.callbackField();
                }
            }
        }, pair);
    }
    //走势图调用
    public void loadData(String issuecount){}
}
